package com.guangfeng.yql.comm.netty.chatroom;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.guangfeng.yql.comm.netty.annotation.AChatRoomMessage;
import com.guangfeng.yql.comm.netty.enumerate.ChatRoomMessageType;
import com.guangfeng.yql.comm.netty.util.NettyAnnotationUtil;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.Map;
import java.util.TreeMap;

public class ChatRoomMessageFactory {

    private final static Map<ChatRoomMessageType, ChatRoomMessage> map = new TreeMap<>();

    static {
        Map<String, ChatRoomMessage> beans = SpringUtil.getBeansOfType(ChatRoomMessage.class);
        beans.forEach((key, value) -> {
            AChatRoomMessage annotation = NettyAnnotationUtil.getAnnotation(value, AChatRoomMessage.class);
            if (annotation != null) {
                map.put(annotation.value(), value);
            }
        });
    }

    public static ChatRoomMessage getChatRoomMessage(TextWebSocketFrame text) {
        try {
            Map<String, Object> json = JSONUtil.parseObj(text.text());
            if (!json.containsKey("status")) {
                return null;
            }
            return map.get(ChatRoomMessageType.getEnum(Integer.valueOf(json.get("status").toString())));
        } catch (RuntimeException e) {
            return null;
        }
    }

}
